package org.example.traffic.questions;

import org.example.traffic.organizationadmin.OrganizationAdmin;
import org.example.traffic.questions.Questions;
import org.example.traffic.questions.QuestionsService;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/questions")
public class QuestionsController {

    private final QuestionsService questionsService;

    public QuestionsController(QuestionsService questionsService) {
        this.questionsService = questionsService;
    }

    // 分页查询视频
    @GetMapping
    public ResponseEntity<Page<Questions>> getOrganizations(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size) {
        Page<Questions> questions = questionsService.getQuestions(page-1, size);
        return ResponseEntity.ok(questions);
    }

    // 根据ID获取问题
    @GetMapping("/{id}")
    public ResponseEntity<Questions> getQuestionById(@PathVariable Integer id) {
        Optional<Questions> question = questionsService.getQuestionById(id);
        return question.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).build());
    }

    // 创建新问题
    @PostMapping
    public ResponseEntity<Questions> createQuestion(@RequestBody Questions question) {
        Questions createdQuestion = questionsService.createQuestion(question);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdQuestion);
    }

    // 更新问题
    @PutMapping("/{id}")
    public ResponseEntity<Questions> updateQuestion(@PathVariable Integer id, @RequestBody Questions updatedQuestion) {
        Questions question = questionsService.updateQuestion(id, updatedQuestion);
        return (question != null) ? ResponseEntity.ok(question)
                : ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    // 删除问题
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteQuestion(@PathVariable Integer id) {
        return (questionsService.deleteQuestion(id)) ? ResponseEntity.status(HttpStatus.NO_CONTENT).build()
                : ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    /**
     * 根据题目名称进行模糊查询
     * @param questionText 题目名称（模糊匹配）
     * @return 符合条件的题目列表
     */
    @GetMapping("/search")
    public List<Questions> searchQuestionsByText(@RequestParam String questionText) {
        return questionsService.findQuestionsByText(questionText);
    }
    /**
     * 验证答案是否正确
     * @param payload 包含题目ID和用户提交的答案
     * @return 如果答案正确返回true，否则返回false
     */
    @PostMapping("/validate-answer")
    public boolean validateAnswer(@RequestBody Map<String, Object> payload) {
        Integer questionId = (Integer) payload.get("questionId");
        String userAnswer = (String) payload.get("userAnswer");
        return questionsService.validateAnswer(questionId, userAnswer);
    }
    /**
     * 计算用户提交答案的总分
     * @param answers 用户提交的答案列表
     * @return 返回用户总分
     */
    @PostMapping("/calculate-total-score")
    public ResponseEntity<Integer> calculateTotalScore(@RequestBody List<Map<String, Object>> answers) {
        int totalScore = questionsService.calculateTotalScore(answers);
        return ResponseEntity.ok(totalScore);
    }
}

